package com.open.capacity.notice.provider.core.http;

import java.io.IOException;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import com.open.capacity.notice.provider.core.constant.CommonConstant;
import com.open.capacity.notice.provider.core.http.interactive.req.ThRequest;
import com.open.capacity.notice.provider.core.http.interactive.res.ThResponse;

import cn.hutool.core.bean.BeanUtil;
@SuppressWarnings("all")
public interface HttpOperations {

	public ThOkHttp3Template getThOkHttp3Template();

	default Map<String, Object> buildHeaders(Map<String, Object> headers) {
		return headers;
	}

	default <REQ extends ThRequest> Map<String, Object> buildBody(REQ request) {
		return BeanUtil.beanToMap(request, false, true).entrySet().stream()
				.filter(entry -> !entry.getKey().equals(CommonConstant.FILTER_STR))
				.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
	}

	default <API extends ApiAdress, REQ extends ThRequest, RES extends ThResponse> RES get(API address, boolean isAuth,
			REQ request, Class<RES> cls, Object... args) throws IOException {
		Map<String, Object> headers = null;
		Map<String, Object> params = buildBody(request);
		if (isAuth) {
			headers = buildHeaders(request.getHeaders());
		}
		return getThOkHttp3Template().get(address, params, cls, args);
	}

	default <API extends ApiAdress, REQ extends ThRequest, RES extends ThResponse> RES post(API address, boolean isAuth,
			REQ request, Class<RES> cls, Object... args) throws IOException {
		Map<String, Object> headers = null;
		Map<String, Object> requestBody = buildBody(request);
		if (isAuth) {
			headers = buildHeaders(request.getHeaders());
		}
		return getThOkHttp3Template().post(address, headers, null, requestBody, cls, args);

	}

	default <API extends ApiAdress, REQ extends ThRequest, RES extends ThResponse> void asyncGet(API address,
			boolean isAuth, REQ request, Class<RES> cls, Consumer<RES> success, Consumer<IOException> failure,
			Object... args) throws IOException {
		Map<String, Object> headers = null;
		if (isAuth) {
			headers = buildHeaders(request.getHeaders());
		}
		Map<String, Object> requestParams = buildBody(request);
		getThOkHttp3Template().asyncGet(address, isAuth, headers, requestParams, cls, success, failure, args);
	}

	default <API extends ApiAdress, REQ extends ThRequest, RES extends ThResponse> void asyncPost(API address,
			boolean isAuth, REQ request, Class<RES> cls, Consumer<RES> success, Consumer<IOException> failure,
			Object... args) throws IOException {
		Map<String, Object> headers = null;
		if (isAuth) {
			headers = buildHeaders(request.getHeaders());
		}
		Map<String, Object> requestBody = buildBody(request);
		getThOkHttp3Template().asyncPost(address, isAuth, headers, null, requestBody, cls, success, failure, args);
	}

}
